<template>
  <div class="supervisor-profile">
    <el-card class="profile-card">
      <template #header>
        <span>Supervisor Profile</span>
      </template>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-card>
            <div class="avatar-container">
              <el-avatar
                  :size="100"
                  :src="userStore.user.avatar || '/placeholder-avatar.png'"
              />
              <div class="avatar-actions">
                <el-button size="small" type="primary" @click="handleAvatarUpload">
                  Change Avatar
                </el-button>
                <input
                    type="file"
                    ref="fileInputRef"
                    style="display: none"
                    accept="image/*"
                    @change="handleFileSelected"
                />
              </div>
            </div>
            <div class="user-info">
              <h3>{{ userStore.user.name || userStore.user.realName || userStore.user.username || 'User' }}</h3>
              <el-tag type="success">Supervisor</el-tag>
            </div>
            <el-divider />
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="Basic Info" name="basic">
              <el-form
                  ref="formRef"
                  :model="formModel"
                  :rules="rules"
                  label-position="left"
                  label-width="100px"
              >
                <el-form-item label="Username" prop="username">
                  <el-input v-model="formModel.username" disabled />
                </el-form-item>
                <el-form-item label="Real Name" prop="realName">
                  <el-input v-model="formModel.realName" placeholder="Please input real name" />
                </el-form-item>
                <el-form-item label="Nickname" prop="nickname">
                  <el-input v-model="formModel.nickname" placeholder="Please input nickname" />
                </el-form-item>
                <el-form-item label="Email" prop="email">
                  <el-input v-model="formModel.email" placeholder="Please input email" />
                </el-form-item>
                <el-form-item label="Phone Number" prop="phone">
                  <el-input v-model="formModel.phone" placeholder="Please input phone number" />
                </el-form-item>
                <el-form-item label="Bio" prop="bio">
                  <el-input
                      v-model="formModel.bio"
                      type="textarea"
                      placeholder="Please input bio"
                      :rows="3"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSubmit">Save Changes</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="Account Security" name="security">
              <el-form
                  ref="passwordFormRef"
                  :model="passwordForm"
                  :rules="passwordRules"
                  label-position="left"
                  label-width="100px"
              >
                <el-form-item label="Current Password" prop="currentPassword">
                  <el-input
                      v-model="passwordForm.currentPassword"
                      type="password"
                      placeholder="Please input current password"
                      show-password
                  />
                </el-form-item>
                <el-form-item label="New Password" prop="newPassword">
                  <el-input
                      v-model="passwordForm.newPassword"
                      type="password"
                      placeholder="Please input new password"
                      show-password
                  />
                </el-form-item>
                <el-form-item label="Confirm New Password" prop="confirmPassword">
                  <el-input
                      v-model="passwordForm.confirmPassword"
                      type="password"
                      placeholder="Please input new password again"
                      show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handlePasswordChange">Update Password</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { useUserStore } from '../../stores/user';
import axios from '../../utils/axios';

// Supervisor dashboard data interface
interface SupervisorDashboardDTO {
  studentCount: number;
  activeToday: number;
  pendingTasks: number;
  weeklyEvents: number;
  studentProjectProgresses: any[];
  recentActivities: any[];
}

const userStore = useUserStore();
const activeTab = ref('basic'); // Initially selected basic information tab
const statsLoading = ref(false); // Add loading status flag
const fileInputRef = ref<HTMLInputElement | null>(null); // File input reference

// User statistics data
const userStats = reactive({
  studentCount: 0 // Initial value set to 0, the actual data will be obtained through the API
});

// Form data
const formModel = ref({
  username: userStore.user.username || '',
  realName: userStore.user.realName || '',
  nickname: userStore.user.nickname || '',
  email: userStore.user.email || '',
  phone: userStore.user.phone || '',
  bio: userStore.user.bio || ''
});

// Form validation rules
const rules = {
  email: [
    {
      required: false,
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: 'Please enter a valid email address',
      trigger: 'blur'
    }
  ],
  phone: [
    {
      required: false,
      pattern: /^1[3-9]\d{9}$/,
      message: 'Please enter a valid phone number',
      trigger: 'blur'
    }
  ]
};

// Password form
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// Password form validation rules
const passwordRules = {
  currentPassword: [
    { required: true, message: 'Please enter the current password', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: 'Please enter a new password', trigger: 'blur' },
    { min: 6, message: 'Password length must be at least 6 characters', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      required: true,
      message: 'Please confirm the new password',
      trigger: 'blur'
    },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('The two passwords entered are inconsistent'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// Form reference
const formRef = ref(null);
const passwordFormRef = ref(null);

// Initialize loading user data
onMounted(async () => {
  try {
    // Get the supervisor dashboard data, including the real number of students
    await fetchSupervisorStats();
  } catch (error) {
    ElMessage.error('Failed to load settings, please try again later');
  }
});

// Handle avatar upload
const handleAvatarUpload = () => {
  // Trigger a hidden file input click event
  if (fileInputRef.value) {
    fileInputRef.value.click();
  }
};

// Handle file selection
const handleFileSelected = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (!target.files || target.files.length === 0) {
    return;
  }

  const file = target.files[0];

  // Check file type
  if (!file.type.startsWith('image/')) {
    ElMessage.error('Please select an image file');
    return;
  }

  // Check file size (limited to 2MB)
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('The image size cannot exceed 2MB');
    return;
  }

  // Create FormData object
  const formData = new FormData();
  formData.append('file', file);

  // Display loading indicator
  const loadingInstance = ElLoading.service({
    text: 'Uploading avatar...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    // Use the existing /api/user/avatar interface to upload the avatar
    const response = await axios.post('/api/user/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    // Update the avatar after successful upload
    ElMessage.success('Avatar uploaded successfully');

    // Update the avatar in the Vuex store
    userStore.setUserAvatar(response.data.url);

    // Reset file input
    if (fileInputRef.value) {
      fileInputRef.value.value = '';
    }
  } catch (error) {
    console.error('Avatar upload failed:', error);
    ElMessage.error('Avatar upload failed, please try again later');
  } finally {
    // Close the loading indicator
    loadingInstance.close();
  }
};

// Handle basic information saving
const handleSubmit = async () => {
  if (!formRef.value) return;

  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // Add API call to save user information here
        // await userStore.updateUserInfo(formModel.value);
        ElMessage.success('User information updated');
      } catch (error) {
        ElMessage.error('Failed to save, please try again later');
      }
    }
  });
};

// Handle password modification
const handlePasswordChange = () => {
  if (!passwordFormRef.value) return;

  passwordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // Add API call to modify the password here
        // await userStore.changePassword(passwordForm.value);
        ElMessage.success('Password updated');
        passwordForm.value.currentPassword = '';
        passwordForm.value.newPassword = '';
        passwordForm.value.confirmPassword = '';
      } catch (error) {
        ElMessage.error('Failed to modify password, please try again later');
      }
    }
  });
};

// Get supervisor dashboard data
const fetchSupervisorStats = async () => {
  statsLoading.value = true;
  try {
    const response = await axios.get<SupervisorDashboardDTO>('/api/dashboard/supervisor/stats');
    // Update student count
    userStats.studentCount = response.data.studentCount;
    console.log('Successfully retrieved supervisor student count:', response.data.studentCount);
  } catch (error) {
    console.error('Failed to retrieve supervisor data:', error);
    ElMessage.error('Failed to retrieve statistics data, please try again later');
  } finally {
    statsLoading.value = false;
  }
};
</script>
<style scoped>
.profile-card {
  margin-bottom: 20px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 15px;
}

.avatar-actions {
  margin-top: 10px;
}

.user-info {
  text-align: center;
  margin-bottom: 15px;
}

.user-info h3 {
  margin: 10px 0 5px;
  font-size: 18px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
  margin-top: 15px;
}

.stat-item {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}


.el-tab-pane {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 10px;
}

.el-tab-pane::-webkit-scrollbar {
  width: 6px;
}

.el-tab-pane::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.el-tab-pane::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.el-form {
  padding-bottom: 10px;
}
</style> 